<template>
  <div>
    <el-tabs type="border-card" v-model="activeName" class="smooth-tabs" @tab-click="handleClick"
             style="max-height: 100%; box-sizing: border-box;">

      <el-tab-pane label="库存表" name="first">
        <div style="overflow-x: auto">
          <el-table :border="true" :stripe="true" :height=tableHeight
                    :data="materialTable.filter(data => {
      const name = data.name? data.name.toString() : '';
      const brand = data.brand? data.brand.toString() : '';
      const model = data.model? data.model.toString() : '';
      return!search ||
             name.toLowerCase().includes(search.toLowerCase()) ||
             brand.toLowerCase().includes(search.toLowerCase()) ||
             model.toLowerCase().includes(search.toLowerCase());
    })" size="mini" @selection-change="handleSelectionChange" id="printArea">
            <el-table-column label="序号" type="index" min-width="5%"></el-table-column>
            <el-table-column label="类别" min-width="6%" disabled>
              <template slot-scope="scope">
                <el-input v-model="scope.row.categoryLargeName" :disabled="editingIndex !== scope.$index"
                          :class="{editable: editingIndex === scope.$index}"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="物料编码" min-width="6%">
              <template slot-scope="scope">
                <el-input v-model="scope.row.code" :disabled="editingIndex !== scope.$index"
                          :class="{editable: editingIndex === scope.$index}"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="名称" min-width="15%">
              <template slot-scope="scope">
                <el-input v-model="scope.row.name" :disabled="editingIndex !== scope.$index"
                          :class="{editable: editingIndex === scope.$index}"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="品牌" min-width="7%">
              <template slot-scope="scope">
                <el-input v-model="scope.row.brand" :disabled="editingIndex !== scope.$index"
                          :class="{editable: editingIndex === scope.$index}"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="规格/型号" min-width="27%">
              <template slot-scope="scope">
                <el-input v-model="scope.row.model" :disabled="editingIndex !== scope.$index"
                          :class="{editable: editingIndex === scope.$index}"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="单位" min-width="5%">
              <template slot-scope="scope">
                <el-input v-model="scope.row.unit" :disabled="editingIndex !== scope.$index"
                          :class="{editable: editingIndex === scope.$index}"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="库存数量" min-width="5%">
              <template slot-scope="scope">
                <el-input v-model="scope.row.number" :disabled="editingIndex !== scope.$index"
                          :class="{editable: editingIndex === scope.$index}"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="含税单价" min-width="7%" v-if="showPriceColumn">
              <template slot-scope="scope">
                <el-input v-model="scope.row.unitPriceIncludingTax" :disabled="editingIndex !== scope.$index"
                          :class="{editable: editingIndex === scope.$index}"></el-input>
              </template>
            </el-table-column>
            <el-table-column type="selection" min-width="5%"></el-table-column>
            <el-table-column min-width="15%">
              <template slot="header" slot-scope="scope">
                <el-input
                    v-model="search" clearable
                    size="mini"
                    placeholder="输入关键字搜索"/>
              </template>
              <template slot-scope="scope">
                <el-button v-if="editVisible || showAllWarehousingRecord"
                           size="mini" type="text"
                           @click="records(scope.row.code)">出入库记录
                </el-button>
                <el-button
                    size="mini" type="text" @click="edit(scope.$index,scope.row)" v-if="editVisible">编辑
                </el-button>
                <el-button
                    size="mini" type="text" @click="update()" v-if="editingIndex === scope.$index">提交
                </el-button>
                <el-button
                    size="mini" type="text" @click="cancel()" v-if="editingIndex === scope.$index">取消
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="display: flex; align-items: center; justify-content: left; gap: 10px; margin-top: 10px;
      border: #1989FA">
          <el-button size="mini" type="primary" @click="addItem()" slot="reference" v-if="editVisible">创建物资</el-button>
          <el-button size="mini" @click="warehousing()" type="primary" slot="reference">入库</el-button>
          <el-button size="mini" type="primary" @click="outbound()">出库</el-button>
          <el-button type="primary" size="mini" @click="currentDiv = 'div3'">盘点</el-button>
          <el-button size="mini" type="primary" @click="printTable()" slot="reference" v-if="editVisible">打印</el-button>
          <el-button size="mini" type="primary" @click="exportWMSTable()" slot="reference" v-if="editVisible">导出Excel
          </el-button>
        </div>
      </el-tab-pane>

      <el-tab-pane label="入库申请记录" name="second">
        <el-table :data="warehousingProcessData" style="width: 100%" row-key="id" border
                  :span-method="(params) => spanMethod(params, warehousingProcessData)" @cell-click="viewWareProcess"
                  :cell-style="cellStyle">
          <el-table-column type="index" label="序号" min-width="5%"></el-table-column>
          <el-table-column prop="serialNumber" label="单号" min-width="8%"></el-table-column>
          <el-table-column prop="creator" label="发起人" min-width="7%"></el-table-column>
          <el-table-column prop="createTime" label="发起时间" min-width="9%"></el-table-column>
          <el-table-column prop="name" label="物资名称" min-width="14%"></el-table-column>
          <el-table-column prop="model" label="型号" min-width="24%"></el-table-column>
          <el-table-column prop="unit" label="单位" min-width="5%"></el-table-column>
          <el-table-column prop="number" label="数量" min-width="5%"></el-table-column>
          <el-table-column prop="project" label="项目号" min-width="16%"></el-table-column>
          <!--        <el-table-column prop="status" label="办理状态"></el-table-column>-->
          <el-table-column prop="processCurrentTask" label="当前节点" min-width="7%"></el-table-column>
        </el-table>
      </el-tab-pane>

      <el-tab-pane label="出库申请记录" name="third">
        <el-table :data="outboundProcessData" style="width: 100%" row-key="id" border
                  :span-method="(params) => spanMethod(params, outboundProcessData)" @cell-click="viewOutProcess"
                  :cell-style="cellStyle">
          <el-table-column type="index" label="序号" min-width="5%"></el-table-column>
          <el-table-column prop="serialNumber" label="单号" min-width="8%"></el-table-column>
          <el-table-column prop="creator" label="发起人" min-width="7%"></el-table-column>
          <el-table-column prop="createTime" label="发起时间" min-width="9%"></el-table-column>
          <el-table-column prop="name" label="物资名称" min-width="14%"></el-table-column>
          <el-table-column prop="model" label="规格/型号" min-width="24%"></el-table-column>
          <el-table-column prop="unit" label="单位" min-width="5%"></el-table-column>
          <el-table-column prop="number" label="数量" min-width="5%"></el-table-column>
          <el-table-column prop="project" label="项目号" min-width="16%"></el-table-column>
          <!--        <el-table-column prop="status" label="办理状态"></el-table-column>-->
          <el-table-column prop="processCurrentTask" label="当前节点" min-width="7%"></el-table-column>
        </el-table>
        <el-button size="mini" type="primary" @click="exportOutboundTable()" style="margin-top: 1rem !important;">导出Excel
        </el-button>
      </el-tab-pane>
    </el-tabs>
    <!--    创建物资子组件-->
    <add-material-item :addItemVisible="addItemVisible"
                       :newItemData="newItemData"
                       @update:addItemVisible="addItemVisible=$event"
                       @addNewItem="handleAddNewItem">
    </add-material-item>
    <!--    入库申请子组件-->
    <warehousing-form :warehousingVisible="warehousingVisible"
                      :warehousingData="warehousingData"
                      :company="company"
                      :date="date"
                      :optionsTaxRate="optionsTaxRate"
                      :optionsAddress="optionsAddress"
                      :purchasePerson="purchasePerson"
                      @update:warehousingVisible="warehousingVisible=$event"
                      @warehousingApplied="handleWarehousingApplied">
    </warehousing-form>
    <!--    出库申请子组件-->
    <out-bound :outboundVisible="outboundVisible"
               :outboundData="outboundData"
               :company="company"
               :date="date"
               :recipient="recipient"
               @update="handleVisibilityChange"
               @outboundApplied="handleOutboundApplied">
    </out-bound>
    <!-- 单项物资出入库记录组件-->
    <material-records :recordVisible="recordVisible"
                      :recordData="recordData"
                      @update:recordVisible="recordVisible=$event">
    </material-records>
  </div>
</template>
<script>
import WarehousingForm from "@/views/WarehousingForm"
import AddMaterialItem from "@/views/AddMaterialItem"
import OutBound from "@/views/OutBound";
import MaterialRecords from "@/views/MaterialRecords";
import PrintWarehousing from "@/views/PrintWarehousing";
import {mapActions, mapGetters} from 'vuex';
import printJS from 'print-js';
import * as XLSX from 'xlsx'

export default {
  name: "wms",
  components: {
    MaterialRecords,
    AddMaterialItem,
    WarehousingForm,
    OutBound,
  },
  data() {
    return {
      materialTable: [{
        categoryName: '',
        code: '',
        name: '',
        brand: '',
        model: '',
        unit: '',
        number: '',
        unitPriceIncludingTax: '',
        positionName: ''
      }],
      showPriceColumn: false,
      showAllOutBoundRecord: false,
      showAllWarehousingRecord: false,
      search: '',
      //创建物资组件订阅参数
      addItemVisible: false,
      newItemData: [{
        code: '',
        categoryLargeName: '',
        categoryLargeSn: '',
        categoryMediumName: '',
        categoryMediumSn: '',
        categoryMiniName: '',
        categoryMiniSn: '',
        sn: '',
        name: '',
        model: '',
        brand: '',
        unit: '',
        referencePrice: ''
      }],
      //入库单组件订阅参数
      warehousingVisible: false,
      warehousingData: [{
        name: '',
        code: '',
        model: '',
        unit: '',
        number: '',
        unitPriceIncludingTax: '',
        taxRate: '',
        project: '',
        positionName: '南通'
      }],
      purchasePerson: JSON.parse(localStorage.user).nickName,
      optionsTaxRate: [
        {value: '0.13', label: '13%'},
        {value: '0.09', label: '9%'},
        {value: '0.06', label: '6%'},
        {value: '0.03', label: '3%'},
        {value: '0.01', label: '1%'}
      ],
      warehousingComment: '',

      //出库单数据
      outboundVisible: false,
      outboundData: [
        {
          name: '',
          code: '',
          model: '',
          unit: '',
          number: '',
          totalPriceTax: '',
          taxRate: '',
          unitPriceBeforeTax: '',
          amountBeforeTax: '',
          project: '',
          positionName: '',
          custodian: ''
        }
      ],
      outboundComment: '',
      recipient: JSON.parse(localStorage.user).nickName,
      //出入库申请公用数据
      company: '赛福斯特',
      date: new Date().toISOString().slice(0, 10),
      optionsAddress: [
        {value: '南通', label: '南通基地'},
        {value: '北京', label: '总部'}
      ],
      selectedRows: [],
      //出入库记录数据
      recordVisible: false,
      recordData: [],
      //编辑物资组件数据
      editingIndex: null,
      editingRow: '',
      editVisible: false,
      editData: [],
      originalData: null,
      //出入库台账
      warehousingProcessData: [],
      outboundProcessData: [],
      //出入库单打印
      processInstanceId: null,
    }
  },
  computed: {
    tableHeight() {
      // 假设页面顶部和底部占用的总高度为 150px
      const offsetHeight = 220; // 调整这个值以适应您的页面布局
      return `calc(100vh - ${offsetHeight}px)`;
    },
    ...mapGetters(['getActiveTab']),
    activeName: {
      get() {
        return this.getActiveTab;
      },
      set(value) {
        this.updateActiveTab(value);
      }
    }
  },
  methods: {
    ...mapActions(['updateActiveTab']),
    edit(index, row) {
      this.editingIndex = index
      this.editingRow = row
      this.originalData = JSON.parse(JSON.stringify(this.editingRow));
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    update() {
      const materialDTO = this.editingRow;
      console.log(JSON.stringify(materialDTO, null, 2))
      // 发送数据到后端
      this.$http.post('/material/updateMaterialItem', materialDTO)
          .then(response => {
            this.$message.success('更新成功');
            this.editingIndex = null; // 重置编辑索引
          })
          .catch(error => {
            this.$message.error('更新失败');
          });
    },
    cancel() {
      if (this.editingIndex !== null) {
        this.materialTable.splice(this.editingIndex, 1, this.originalData); // 恢复原始数据
        this.editingIndex = null;
        this.originalData = null; // 清除保存的原始数据
      }
    },
    handleSelectionChange(val) {
      this.selectedRows = val;
    },
    warehousing() {
      this.warehousingData = this.selectedRows.map(row => ({
        name: row.name,
        code: row.code,
        model: row.model,
        unit: row.unit,
        unitPriceIncludingTax: row.unitPriceIncludingTax,
        taxRate: '0.13',
        positionName: '南通'
        // 根据需要复制其他字段
      }));
      this.warehousingVisible = true;
    },
    viewWareProcess(row, column, cell, event) {
      if (column.property === 'serialNumber') {
        console.log(row.processInstanceId)
        this.updateActiveTab(this.activeName);
        this.$router.push({name: 'PrintWarehousing', params: {processInstanceId: row.processInstanceId}});
      }
    },
    viewOutProcess(row, column, cell, event) {
      if (column.property === 'serialNumber') {
        console.log(row.processInstanceId)
        this.updateActiveTab(this.activeName);
        this.$router.push({name: 'PrintOutbound', params: {processInstanceId: row.processInstanceId}});
      }
    },
    cellStyle({row, column, rowIndex, columnIndex}) {
      if (column.property === 'serialNumber') {
        return {
          color: '#1989FA', // 蓝色文本
          textDecoration: 'underline', // 下划线
          cursor: 'pointer', // 鼠标悬停时显示手型
        };
      }
      return {};
    },
    //父组件中的出库按钮，点击后根据所选物资code，查询出对应物资信息
    outbound() {
      const codes = this.selectedRows.map(row => ({code: row.code}));
      this.$http.post("/material/selectApplyOutboundByCodes/", codes).then((response) => {
        if (response.data.code == 1) {
          this.outboundData = response.data.data
          console.log(`获取出库数据成功:${this.outboundData}`)
        } else {
          console.log("获取出库数据失败")
        }
      })
      this.outboundVisible = true;
    },
    addItem() {
      this.addItemVisible = true;
    },
    formatter(row, column) {
      return row.address;
    },
    filterTag(value, row) {
      return row.tag === value;
    },
    filterHandler(value, row, column) {
      const property = column['property'];
      return row[property] === value;
    },
    checkPermissions() {
      const userInfo = JSON.parse(localStorage.getItem('user')); // 确保这里是正确的键名
      this.showPriceColumn = userInfo.authorities.some(authority => authority.authority === 'ROLE_SHOW_PRICE');
      this.editVisible = (userInfo.username === 'cuijin' || userInfo.username === 'cfswt');
      this.showAllOutBoundRecord = (userInfo.username === 'binglina') || (userInfo.username === 'zhaohongyu') || (userInfo.username === 'chaisanpeng') || (userInfo.username === 'tangyan');
      this.showAllWarehousingRecord = (userInfo.username === 'zhaohongyu') || (userInfo.username === 'binglina') || (userInfo.username === 'chaisanpeng') || (userInfo.username === 'tangyan')
    },
    handleAddNewItem() {
      const newMaterialDTO = this.newItemData
      console.log(newMaterialDTO)
      this.$http.post("/material/add", newMaterialDTO).then((response) => {
        if (response.data.code == 1) {
          this.$message({
            showClose: true,
            message: '创建物资成功',
            type: 'success'
          });
        } else {
          this.$message({
            showClose: true,
            message: '提交失败，请联系管理员',
            type: 'error'
          });
        }
      })
    },
    //父组件监听入库单子组件方法：更新子组件提交的申请数据，发送数据到后端做持久化
    handleWarehousingApplied(updatedData) {
      this.$http.post("/material/warehousing", updatedData).then((response) => {
        if (response.data.code == 1) {
          this.$message({
            showClose: true,
            message: '提交成功，下一步经办人:赵红玉',
            type: 'success'
          });
        } else {
          this.$message({
            showClose: true,
            message: '提交失败，请联系管理员',
            type: 'error'
          });
        }
      })
    },
    handleVisibilityChange(newVisibility) {
      this.outboundVisible = newVisibility;
    },
    //父组件监听出库子组件方法：更新子组件提交的申请数据，及发送数据到后端做持久化
    handleOutboundApplied(updatedData) {
      this.$http.post("/material/outbound", updatedData)
          .then((response) => {
            if (response.data.code == 1) {
              this.$message({showClose: true, message: '提交成功,下一步审核人:柴三朋', type: 'success'})
            } else {
              this.$message({showClose: true, message: '提交失败，请重新登陆尝试', type: 'error'})
            }
          })
    },
    records(code) {
      this.$http.get("/material/record/" + code).then((response) => {
        if (response.data.code == 1) {
          this.recordData = response.data.data
          console.log(this.recordData)
        } else {
          this.$message({
            showClose: true,
            message: '获取数据失败，请联系管理员',
            type: 'error'
          });
        }
      })
      this.recordVisible = true
    },
    spanMethod({row, column, rowIndex, columnIndex}, data) {
      if (!data || data.length === 0) {
        return [1, 1]; // 如果数据为空，返回默认的单元格跨度
      }
      // 合并的列索引
      const mergeColumns = [1, 2, 3, 9]; // 1: 序号, 2: 发起人, 3: 发起时间,  9: 当前节点

      if (mergeColumns.includes(columnIndex)) {
        if (rowIndex > 0 && data[rowIndex].serialNumber === data[rowIndex - 1].serialNumber) {
          return [0, 0]; // 当前行与上一行的serialNumber相同，不显示当前单元格
        } else {
          let span = 1;
          while (rowIndex + span < data.length &&
          data[rowIndex + span].serialNumber === data[rowIndex].serialNumber) {
            span++; // 计算有多少行的serialNumber与当前行相同
          }
          return [span, 1]; // 合并这些行
        }
      }
    },
    printTable() {
      printJS({
        printable: 'printArea',
        type: 'html',
        style: `
           .el-table {
                font-size: 13px;
                width: 100%;
            }
           .el-table tr th,
           .el-table tr td {
                padding: 0px;
                white-space: nowrap;
                border-collapse: collapse !important;
                line-height: 20px; box-sizing: border-box !important;
                text-align: left;
                border: 1px solid #eee;
                font-weight: 100;
            }
           .el-table tr th:nth-child(10),
           .el-table tr td:nth-child(10) { display:none !important;  }
           .el-table tr th:nth-child(11),
           .el-table tr td:nth-child(11) { display:none !important;  }
           .el-input__inner {
                width: 100% !important;
                box-sizing: border-box !important;
                padding: 0;
                border: none !important; font-size:12px !important; font-weight:100 !important;
                margin: 0; background-color:transparent !important;
            }
        `,
        scanStyles: true,
      });
      console.log("打印完成");
    },
    exportWMSTable() {
      // 获取表格数据
      const tableData = this.materialTable.filter(data => {
        const name = data.name ? data.name.toString() : '';
        const brand = data.brand ? data.brand.toString() : '';
        const model = data.model ? data.model.toString() : '';
        return !this.search ||
            name.toLowerCase().includes(this.search.toLowerCase()) ||
            brand.toLowerCase().includes(this.search.toLowerCase()) ||
            model.toLowerCase().includes(this.search.toLowerCase());
      });

      // 定义表头
      const headers = [
        '序号', '类别', '物料编码', '名称', '品牌', '规格/型号', '单位', '库存数量', '含税单价'
      ];

      // 转换数据为二维数组，并手动添加序号
      const data = tableData.map((item, index) => [
        index + 1, // 手动添加序号
        item.categoryLargeName,
        item.code,
        item.name,
        item.brand,
        item.model,
        item.unit,
        item.number,
        item.unitPriceIncludingTax
      ]);

      // 在数据开头添加表头
      data.unshift(headers);

      // 创建工作簿
      const ws = XLSX.utils.aoa_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // 获取当前日期
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.getDate()).padStart(2, '0');
      const formattedDate = `${year}${month}${day}`;

      // 拼接文件名
      const fileName = `${formattedDate}物资表.xlsx`;

      // 导出为 Excel 文件
      XLSX.writeFile(wb, fileName);
    },
    exportOutboundTable() {
      // 获取表格数据
      const tableData = this.outboundProcessData

      // 定义表头
      const headers = [
        '序号', '单号', '发起人', '发起时间', '物资名称', '规格/型号', '单位', '数量', '项目号', '当前节点'
      ];

      // 转换数据为二维数组，并手动添加序号
      const data = tableData.map((item, index) => [
        index + 1, // 手动添加序号
        item.serialNumber,
        item.creator,
        item.createTime,
        item.name,
        item.model,
        item.unit,
        item.number,
        item.project,
        item.processCurrentTask
      ]);

      // 在数据开头添加表头
      data.unshift(headers);

      // 创建工作簿
      const ws = XLSX.utils.aoa_to_sheet(data);
      const wb = XLSX.utils.book_new();
      XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

      // 获取当前日期
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.getDate()).padStart(2, '0');
      const formattedDate = `${year}${month}${day}`;

      // 拼接文件名
      const fileName = `${formattedDate}出库表.xlsx`;

      // 导出为 Excel 文件
      XLSX.writeFile(wb, fileName);
    }
  },
  mounted() {
    this.checkPermissions();
    // 获取材料数据
    this.$http.get("/material").then((response) => {
      console.log(`物资总表:${JSON.stringify(response.data.data)}`)
      if (response.data.code == 1) {
        this.materialTable = response.data.data;
      } else {
        this.$message({
          showClose: true,
          message: '获取数据失败，请联系管理员',
          type: 'error'
        });
      }
    });
    // 根据权限获取出入库数据
    const warehousingUrl = (this.editVisible || this.showAllWarehousingRecord) ? "/material/all_warehousing_process" : "/material/warehousing_process";
    const outboundUrl = (this.editVisible || this.showAllOutBoundRecord) ? "/material/all_outbound_process" : "/material/outbound_process";
    this.$http.get(warehousingUrl).then((response) => {
      if (response.data.code == 1) {
        this.warehousingProcessData = response.data.data;
      }
    });
    this.$http.get(outboundUrl).then((response) => {
      if (response.data.code == 1) {
        this.outboundProcessData = response.data.data;
        console.log(JSON.stringify(this.outboundProcessData, null, 2))
      }
    });
  }
}
</script>

<style scoped>
::v-deep .editable {
  border-bottom: 1px solid #409EFF; /* Element UI 主题蓝色 */
}
</style>